<template>
  <lay-container :fluid="true" style="padding: 10px">
    <lay-row :span="24" style="display: flex">
      <lay-col style="max-width: 400px" :xs="24">
        <lay-card shadow="hover" class="info-user">
          <div style="text-align: center">
            <lay-avatar :src="resolveImgPath(currentUserProfileTemplate.avatar)" class="user-avatar"
                        @click="toImport()"></lay-avatar>
            <div class="user-name">{{ currentUserProfileTemplate.nickName }}</div>
            <div class="user-briefing">{{ currentUserProfileTemplate.remark }}</div>
          </div>

          <lay-row>
            <lay-icon type="layui-icon-username"></lay-icon
            >&nbsp;&nbsp;&nbsp;资深前端工程师
          </lay-row>
          <lay-row>
            <lay-icon type="layui-icon-cellphone"></lay-icon
            >&nbsp;&nbsp;&nbsp;{{ currentUserProfileTemplate.telNo }}
          </lay-row>
          <lay-row>
            <lay-icon type="layui-icon-template"></lay-icon
            >&nbsp;&nbsp;&nbsp;{{ sysDeptEntity.deptName }}
          </lay-row>

          <lay-line border-style="dashed" border-width="1px"></lay-line>
          <h1 style="margin: 10px 0">标签</h1>
          <template v-for="tag in tagsList" :key="tag.id">
            <lay-tag style="margin: 0 6px 6px 0">
              &nbsp;<lay-badge type="dot" :theme="tag.theme" ripple></lay-badge>
              &nbsp;&nbsp;{{ tag.tag }}
            </lay-tag>
          </template>
        </lay-card>
      </lay-col>
      <lay-col style="flex: 1; background-color: #fff" :xs="24">
        <lay-tab type="brief" v-model="activeTab">
          <lay-tab-item title="基本信息" id="baseInfo">
            <div class="tab-content">
              <lay-form
                  :model="sysUserVo"
                  ref="profileFormRef"
                  size="sm"
                  label-position="left"
              >
                <lay-form-item label="用户名" prop="userName">
                  <lay-input v-model="sysUserVo.userName" :disabled="true"></lay-input>
                </lay-form-item>
                <lay-form-item label="昵称" prop="nickName" required>
                  <lay-input v-model="sysUserVo.nickName" allow-clear></lay-input>
                </lay-form-item>
                <lay-form-item label="性别" prop="gender">
                  <lay-select
                      v-model="sysUserVo.gender"
                      style="width: 100%"
                      placeholder="请选择性别"
                      :options="sysGenderListSelect"
                      :items="sysGenderListSelect"
                  >
                  </lay-select>
                </lay-form-item>
                <lay-form-item label="联系电话" prop="telNo" required>
                  <lay-input
                      v-model="sysUserVo.telNo"
                      type="phone"
                      allow-clear
                  ></lay-input>
                </lay-form-item>
                <lay-form-item label="邮箱" prop="email">
                  <lay-input
                      v-model="sysUserVo.email"
                      type="email"
                      allow-clear
                  ></lay-input>
                </lay-form-item>
                <lay-form-item label="个人简介" prop="desc">
                  <lay-textarea
                      placeholder="还没有个人简介哦~"
                      v-model="sysUserVo.remark"
                      show-count :maxlength="500"
                  ></lay-textarea>
                </lay-form-item>
                <lay-form-item style="text-align: center">
                  <lay-button type="primary" @click="profileForm()">提交</lay-button>
                  <lay-button @click="profileFormClearValidate()">清除校验</lay-button>
                  <lay-button @click="profileFormReset()">重置表单</lay-button>
                </lay-form-item>
              </lay-form>
            </div>
          </lay-tab-item>
          <lay-tab-item title="账号绑定" id="bindingInfo">
            <div class="tab-content" style="max-width: unset">
              <template v-for="item in bindingAccountList" :key="item.id">
                <div class="account-item">
                  <div
                      v-if="item.icon != ''"
                      style="width: 45px; display: inline-block"
                  >
                    <lay-icon
                        :type="item.icon"
                        :color="item.color"
                        size="34px"
                    ></lay-icon>
                  </div>
                  <div class="account-desc">
                    <div style="color: #000000e0">{{ item.title }}</div>
                    <div>{{ item.desc }}</div>
                  </div>
                  <div class="account-option">
                    {{ item.option }}
                  </div>
                </div>
              </template>
            </div>
          </lay-tab-item>
        </lay-tab>
      </lay-col>
    </lay-row>
    <lay-layer
        v-model="visibleImport"
        title="上传头像"
        :area="['380px', '600px']"
    >
      <lay-upload
          class="target"
          :url="ossPath"
          v-model="updateFileList"
          field="file"
          acceptMime="image/jpeg,image/png,image/gif,image/webp"
          :auto="false"
          :drag="true"
          @on-change="uploadOnChange"
      >
        <template #preview>
          <div style="width: 100%;text-align: center;">
            只能上传小于10MB的文件
          </div>
          <div>
            <img v-if="previewAvatar" :src="parseImgPath(previewAvatar)"
                 style="width: 300px; height: 300px; object-fit: cover;"
                 alt="#">
          </div>
        </template>
      </lay-upload>
      <div style="width: 100%;margin-top: 40px; text-align: center">
        <lay-button size="sm" type="primary" @click="toUpload()">上传</lay-button>
      </div>
    </lay-layer>
  </lay-container>
</template>

<script lang="ts">
/**
 * 创建组件时要添加name，否则在使用keep-alive时就会失效
 */
export default {
  name: "Profile",
};
</script>
<script lang="ts" setup>
import {onMounted, ref} from 'vue'
import {layer} from '@layui/layer-vue'
import {SysDictValueEntity} from "../../../types/system/Dict";
import {Constants, loadSysDictValue, sysDictValueSelect} from "../../../util/UDict";
import {SysUserVo} from "../../../types/system/User";
import {findDeptById} from "../../../api/system/Dept";
import {SysDeptEntity} from "../../../types/system/Dept";
import {avatarUpdate, findCurrentUserProfile, saveUserInfo, userImport} from "../../../api/system/User";
import {refresh} from "../../../util/UCommon";
import {useCryptStore} from "../../../store/crypt";
import {parseImgPath} from "../../../util/UImage";
import {upload, uploadTemp} from "../../../api/system/Oss";
import {useUserStore} from "../../../store/user";

/* INIT*/
onMounted(async () => {
  await loadDictValue()
  await loadSysDeptEntity();
  await loadCurrentUserInfo()
})
/* INIT*/

/* VAR */
const ossPath = import.meta.env.VITE_APP_AVATAR_UPLOAD_PATH
const userStore = useUserStore();
const $crypt = useCryptStore();
const sysGenderList = ref<Array<SysDictValueEntity>>();
const sysGenderListSelect = ref<Array<SysDictValueEntity>>();
const activeTab = ref('baseInfo')
const profileFormRef = ref()
const sysUserVo = ref<SysUserVo>({})
const sysDeptEntity = ref<SysDeptEntity>({})
const currentUserProfileTemplate = ref({});
const tagsList = ref([
  {id: 1, tag: '雪', theme: 'blue'},
  {id: 2, tag: '风是从哪儿来wu', theme: ''},
  {id: 3, tag: '漫游星河', theme: 'orange'},
  {id: 4, tag: '春日之花', theme: 'green'},
  {id: 5, tag: 'Hey', theme: 'cyan'},
  {id: 6, tag: '风吹一夏', theme: ''}
])
const bindingAccountList = ref([
  {
    id: 1,
    title: '密保手机',
    desc: '已绑定手机: 12345678901',
    option: '去修改',
    icon: ''
  },
  {
    id: 2,
    title: '密保邮箱',
    desc: '已绑定邮箱: email@layui-vue',
    option: '去修改',
    icon: ''
  },
  {
    id: 3,
    title: '密保问题',
    desc: '未设置密保问题',
    option: '去设置',
    icon: ''
  },
  {
    id: 4,
    title: '绑定QQ',
    desc: '当前未绑定QQ账号',
    option: '去绑定',
    icon: 'layui-icon-login-qq',
    color: '#3492ed'
  },
  {
    id: 5,
    title: '绑定微信',
    desc: '当前未绑定绑定微信账号',
    option: '去绑定',
    icon: 'layui-icon-login-wechat',
    color: '#4daf29'
  },
  {
    id: 6,
    title: '绑定微博',
    desc: '当前未绑定绑定微博账号',
    option: '去绑定',
    icon: 'layui-icon-login-weibo',
    color: '#e6162d'
  }
])
const visibleImport = ref(false)
const fileList = ref([])
const uploadAvatar = ref();
const previewAvatar = ref<any>('')
const updateFileList = ref([])
/* VAR */

/* FUNCTION*/
const loadCurrentUserInfo = () => {
  findCurrentUserProfile().then((res: any) => {
    if (res.code === 200) {
      $crypt.decryptAes(res.data).then((decryptAes: any) => {
        let decrypt = JSON.parse(decryptAes);
        currentUserProfileTemplate.value = {...decrypt};
        sysUserVo.value = {...decrypt};
      });
    }
  })

}

const loadSysDeptEntity = async () => {
  const {data, code} = await findDeptById()
  if (code === 200) {
    sysDeptEntity.value = data;
  }
}

const loadDictValue = async () => {
  sysGenderList.value = await loadSysDictValue(Constants.SYS_GENDER)
  sysGenderListSelect.value = await sysDictValueSelect(sysGenderList.value)
}

function profileForm() {
  profileFormRef.value.validate((isValidate: boolean, model: any, errors: any) => {
        if (isValidate) {
          saveUserInfo(model).then(async (res: any) => {
            if (res.code === 200) {
              refresh()
              layer.msg(res.msg, {icon: 1})
            }
          }).catch(e => {
            layer.confirm(e.msg, {icon: 2})
          })
        }
      }
      //   layer.open({
      //     type: 1,
      //     title: '表单提交结果',
      //     content: `<div style="padding: 10px"><p>是否通过 : ${isValidate}</p> <p>表单数据 : ${JSON.stringify(
      //         model
      //     )} </p> <p>错误信息 : ${JSON.stringify(errors)}</p></div>`,
      //     shade: false,
      //     isHtmlFragment: true,
      //     btn: [
      //       {
      //         text: '确认',
      //         callback(index: Number) {
      //           saveUserInfo(model).then((res: any) => {
      //             if (res.code === 200) {
      //               layer.close(index)
      //             }
      //           }).catch(e => {
      //             layer.confirm(e.msg, {icon: 2})
      //           })
      //         }
      //       }
      //     ],
      //     area: '500px'
      //   })
      // }
  )
}

function profileFormClearValidate() {
  profileFormRef.value.clearValidate()
}

function profileFormReset() {
  sysUserVo.value = {...currentUserProfileTemplate.value};
  // profileFormRef.value.reset()
}

function toImport() {
  visibleImport.value = true
}

function toUpload() {
  if (updateFileList.value && updateFileList.value.length > 0) {
    upload(updateFileList.value).then((res: any) => {
      if (res.code === 200) {
        let url = res.data[0].url;
        if (res.data && res.data.length > 0 && url) {
          avatarUpdate(url).then((avatarUpdateRes: any) => {
            if (avatarUpdateRes.code === 200) {
              layer.msg(avatarUpdateRes.msg, {icon: 1})
              userStore.userInfo.avatar = url
              currentUserProfileTemplate.value.avatar = url
            }
          })
          visibleImport.value = false
        }
      }
    })
  }
}

function resolveImgPath(imgPath: string) {
  return parseImgPath(imgPath)
}

function uploadOnChange(file: any) {
  uploadTemp(file).then((res: any) => {
    if (res.code === 200) {
      if (res.data) {
        previewAvatar.value = res.data.url
      }
    }
  })
}

/* FUNCTION*/


</script>

<style scoped>
.layui-tag .layui-tag-text {
  margin: 0 8px 8px 0;
}

.info-user {
  max-width: 400px;
  min-width: 320px;
  padding: 20px;
  margin-right: 10px;
}

.user-avatar {
  width: 200px;
  height: 200px;
  border-radius: 50%;
  cursor: pointer;
}

.user-name {
  font-size: 24px;
  margin: 15px;
}

.user-briefing {
  color: #0006;
  font-size: 14px;
  margin-bottom: 10px;
}

.header-title {
  font-size: 20px;
  font-weight: 500;
  margin-top: 12px;
  margin-bottom: 20px;
}

.header-describe {
  font-size: 14px;
  margin-bottom: 12px;
}

.tab-content {
  height: 368px;
  max-width: 500px;
  padding: 0 20px;
  background-color: #fff;
}

.account-item {
  display: flex;
  width: 99%;
  height: 41px;
  line-height: 43px;
  margin-right: 10px;
  padding: 12px 0;
  border-bottom: #ccc solid 1px;
}

.account-item:last-child {
  border-bottom: none;
}

.account-desc {
  flex: 1;
  color: #0006;
  line-height: 24px;
  display: inline-block;
}

.account-option {
  width: 45px;
  display: inline-block;
  color: var(--global-primary-color);
}

.target {
  width: 100%;
  height: 440px;
  display: flex;
  /*justify-content: center;*/
  flex-direction: column;
  align-items: center;
}
</style>
